//
//  BBBRefreshControl.swift
//  波波微博
//
//  Created by wave on 15/8/4.
//  Copyright © 2015年 wave. All rights reserved.
//

import UIKit

//下拉刷新的偏移量,超出之后,翻转动画
private let refreshPullOffset: CGFloat = -60

class BBBRefreshControl: UIRefreshControl {

    //重写系统的endRefreshing函数,让homeVC的loadData调用这个方法的时候里边就会有stop函数
    override func endRefreshing() {
        super.endRefreshing()

        refreshView.stopLoading()
    }
    
    //构造函数
    override init() {
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
//        super.init(coder: aDecoder)
    }

    
    private func setupUI(){
        
        //添加监听KVO
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        tintColor = UIColor.clearColor()
        
        //添加控件
        addSubview(refreshView)
        
        //设置布局
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: BBBRefreshView.refreshView().bounds.size)
        
    }
    
    //KVO
    /*
        向下拉表格,y值越来越小
        向上推表格,y值越来越大
        从表格顶部向下拉,y值是负数
        拖拽到一定程度,会自动进入刷新状态
    */
    //定义一个旋转的标记,一个开关
    private var rotateFlag = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //判断是否开始刷新,如果进入刷新状态,播放加载动画
        if refreshing{
        
            refreshView.startLoading()
        }
        
        if frame.origin.y > 0 {
            
            return
        }else if frame.origin.y < refreshPullOffset && !refreshView.rotateFlag{
            
            refreshView.rotateFlag = true
        }else if frame.origin.y > refreshPullOffset && refreshView.rotateFlag{
            
            refreshView.rotateFlag = false
        }
    }
    
    deinit{
    
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    //懒加载控件
    private lazy var refreshView:BBBRefreshView = BBBRefreshView.refreshView()
    
}


//下拉刷新视图,--- 负责显示动画
class BBBRefreshView: UIView{

    //小剪头
    @IBOutlet weak var arrowIcon: UIImageView!
    //小菊花
    @IBOutlet weak var camomileIcon: UIImageView!
    //带剪头的View
    @IBOutlet weak var arrowView: UIView!
    
    
    
    //旋转标记
    private var rotateFlag = false{
        didSet{
            
            rotateTipIcon()
        }
    }
    
    //从xib加载刷新视图
    class func refreshView() -> BBBRefreshView{
        
        return NSBundle.mainBundle().loadNibNamed("tipView", owner: nil, options: nil).last as! BBBRefreshView
    }
    
    
    private func rotateTipIcon(){
        
        //在块代码动画中,旋转会就近原则,默认顺时针寻找方向
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(-M_PI + 0.01)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.arrowIcon.transform = CGAffineTransformRotate(self.arrowIcon.transform,angle)
        }
    }
    
    //开始加载函数
    private func startLoading(){
    
        //判断动画是否已经被添加
        if arrowIcon.layer.animationForKey("loadingAnim") != nil{
        
            return
        }
        
        //1. 隐藏提示视图
        arrowView.hidden = true
        
        //2. 定义动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        
        //3. 添加动画
        camomileIcon.layer.addAnimation(anim, forKey: "loadingAnim")
    }
    
    //停止加载动画
    private func stopLoading(){
    
        arrowView.hidden = false
        
        camomileIcon.layer.removeAllAnimations()
    }
}








